package com.media.controller;

import com.media.bean.UserBean;
import com.media.service.UserService;
import com.media.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user")
public class UserController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");

        UserBean userBean = new UserBean();

        userBean.setUsername(request.getParameter("username"));
        userBean.setPassword(request.getParameter("password"));

        UserService userService = new UserServiceImpl();
        if("addUser".equals(method)){
            try {
                int count = userService.addUser(userBean);
                if(count == 0){
                    response.sendRedirect("");
                }else{
                    response.sendRedirect("home.jsp");
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }

        if("editUser".equals(method)){
            userBean.setId(Integer.parseInt(request.getParameter("id")));
            userService.editUser(userBean);
        }

        if("deleteUser".equals(method)){
            userService.deleteUserById(Integer.parseInt(request.getParameter("id")));
        }
    }
}
